import React, { useState, useEffect } from 'react';
import { useAuth } from '../context/AuthContext';

export default function Transfer() {
  const { user } = useAuth();
  const [toId, setToId] = useState('');
  const [amount, setAmount] = useState('');
  const [records, setRecords] = useState([]);
  const [balance, setBalance] = useState(0);
  const [rechargeAmount, setRechargeAmount] = useState('');

  useEffect(() => {
    if (user) {
      fetchRecords(user.student_id);
      fetchBalance(user.student_id);
    }
  }, [user]);

  const fetchRecords = async (sid) => {
    if (!sid) return;
    const res = await fetch(`/api/transfer/${sid}`);
    const data = await res.json();
    if (data.success) setRecords(data.data);
  };

  const fetchBalance = async (sid) => {
    if (!sid) return;
    const res = await fetch(`/api/balance/${sid}`);
    const data = await res.json();
    if (data.success) setBalance(data.balance);
  };

  const handleTransfer = async (e) => {
    e.preventDefault();
    if (!user || !toId || !amount) {
      alert('请填写完整信息');
      return;
    }
    const res = await fetch('/api/transfer', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ from_id: user.student_id, to_id: toId, amount })
    });
    const data = await res.json();
    if (data.success) {
      setToId('');
      setAmount('');
      fetchRecords(user.student_id);
      fetchBalance(user.student_id);
    } else {
      alert(data.message || '转账失败');
    }
  };

  const handleRecharge = async (e) => {
    e.preventDefault();
    if (!user || !rechargeAmount) {
      alert('请输入充值金额');
      return;
    }
    const res = await fetch('/api/recharge', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ student_id: user.student_id, amount: rechargeAmount })
    });
    const data = await res.json();
    if (data.success) {
      setRechargeAmount('');
      fetchBalance(user.student_id);
      alert('充值成功');
    } else {
      alert(data.message || '充值失败');
    }
  };

  return (
    <div className="card">
      <h2>好友转账</h2>
      <div style={{ marginBottom: 16 }}>
        <b>当前余额：</b><span style={{ color: '#1976d2', fontWeight: 600 }}>{balance}</span> 元
        <form onSubmit={handleRecharge} style={{ display: 'inline-block', marginLeft: 24 }}>
          <input type="number" placeholder="充值金额" value={rechargeAmount} onChange={e => setRechargeAmount(e.target.value)} style={{ width: 100 }} />
          <button type="submit" style={{ marginLeft: 8 }}>充值</button>
        </form>
      </div>
      <form onSubmit={handleTransfer} style={{ marginBottom: 20, display: 'flex', gap: 12 }}>
        <input type="text" placeholder="好友学号" value={toId} onChange={e => setToId(e.target.value)} />
        <input type="number" placeholder="金额" value={amount} onChange={e => setAmount(e.target.value)} style={{ width: 80 }} />
        <button type="submit">转账</button>
      </form>
      <h3>转账记录</h3>
      <table>
        <thead>
          <tr><th>转出</th><th>转入</th><th>金额</th><th>时间</th></tr>
        </thead>
        <tbody>
          {records.map(r => (
            <tr key={r.transfer_id}>
              <td>{r.from_id}</td>
              <td>{r.to_id}</td>
              <td>{r.amount}</td>
              <td>{new Date(r.transfer_time).toLocaleString()}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
} 